package com.app.shortvideo.config

import com.app.shortvideo.net.CommonService
import com.app.shortvideo.net.base.BuildAPI.buildAPISevers
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class ConfigManager private constructor() {

    var mConfigInfo: ConfigInfo? = null

    fun getServerConfigInfo() {
        if (mConfigInfo == null) {
            val json = SPUtils.getInstance().getString(SPConst.KEY_CONFIG)
            if (!json.isNullOrEmpty()) {
                mConfigInfo = GsonUtils.fromJson(json, ConfigInfo::class.java)
            }
        }
        CoroutineScope(Dispatchers.IO).launch(CoroutineExceptionHandler { _, throwable ->
            run {

            }
        }) {
            buildAPISevers(CommonService::class.java).apply {
                val rsp = configInfo()
                run {
                    if (rsp.isSuccess) {
                        setConfigInfo(rsp.data)
                    }
                }
            }
        }
    }

    private fun setConfigInfo(config: ConfigInfo?) {
        config ?: return
        mConfigInfo = config
        SPUtils.getInstance().put(SPConst.KEY_CONFIG, GsonUtils.toJson(mConfigInfo))
    }

    fun getConfig(): ConfigInfo? {
        return mConfigInfo
    }

    companion object {
        private var mInstance: ConfigManager? = null

        @Synchronized
        fun getInstance(): ConfigManager? {
            if (mInstance == null) {
                mInstance = ConfigManager()
            }
            return mInstance
        }
    }
}